# __init__.py ：初始化文件，创建Flask应用

from flask import Flask,request
from flask_socketio import SocketIO, join_room,emit
from .data_blueprint import data_bp, connected_users, sid_to_username
from .user_blueprint import user_bp
from .exts import *
from .influxdb_io import InfluxdbIO


# socketio = SocketIO()
socketio = SocketIO(cors_allowed_origins="*", async_mode='eventlet')


def create_app():
    app = Flask(__name__)
    # 注册蓝图
    app.register_blueprint(blueprint=user_bp)
    app.register_blueprint(blueprint=data_bp)

    #配置数据库

    USERNAME = 'root'
    PASSWORD = '123456'
    HOSTNAME = 'localhost'
    PORT = '3306'
    DATABASE = 'har'
    # 格式： mysql + pymysql: // USERNAME: PASSWORD @ HOSTNAME:PORT / DATABASE
    # 配置URL
    DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}'.format(
        USERNAME,
        PASSWORD,
        HOSTNAME,
        PORT,
        DATABASE
    )
    # 这样写会出现循环引用问题
    # app.influxdb_io = InfluxdbIO(st.default_url, st.default_token, st.default_org)

    # 创建 InfluxdbIO 实例并存储在 app.config 中
    app.config['INFLUXDB_IO'] = InfluxdbIO()

    app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    init_exts(app=app)

    socketio.init_app(app)
    app.socketio = socketio

    return app

# 客户端连接时加入房间
@socketio.on('connect')
def handle_connect():
    join_room('wit_data_room')
    print('Client connected')

